#include "client.h"

int main()
{
    int clientfd = tcpConnect("192.168.19.131", 8080);

    char buf[128] = {0};

    //4. 使用select进行监听
    fd_set rdset;
    train_t t;
    while(1) {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(clientfd, &rdset);
        
        int nready = select(clientfd + 1, &rdset, NULL, NULL, NULL);
        printf("nready:%d\n", nready);
        if(FD_ISSET(STDIN_FILENO, &rdset)) {
            //读取标准输入中的数据
            memset(buf, 0, sizeof(buf));
            int ret = read(STDIN_FILENO, buf, sizeof(buf));
            if(0 == ret) {
                printf("byebye.\n");
                break;
            }
            memset(&t, 0, sizeof(t));
            //解析命令行
            buf[strlen(buf)-1] = '\0';
            parseCommand(buf, strlen(buf) - 1, &t);
            sendn(clientfd, &t, 4 + 4 + t.len);

            if(t.type  == CMD_TYPE_PUTS){
                transferFile(clientfd, t.buff);
                continue;
            }
            if(t.type == CMD_TYPE_GETS){
                char buff[1000] = {0};
                int file_name_len = 0;
                ret = recv(clientfd, &file_name_len, sizeof(int), 0);
                recv(clientfd, buff, file_name_len, 0);
                if(strcmp(buff, "error") == 0)
                {
                    printf("传输失败\n");
                    continue;
                }

                printf("filename: %s\n", buff);

                off_t lenth = 0;
                recv(clientfd, &lenth, sizeof(off_t), 0);
                printf("length: %ld\n", lenth);
                off_t currsize = 0;
                double percent = 0;

                int fd = open(buff, O_CREAT | O_RDWR, 0666);
                while(1){
                    memset(buff, 0, sizeof(buff));
                    int file_len = 0;
                    recv(clientfd, &file_len, sizeof(int), MSG_WAITALL);
                    if(file_len != 1000) {
                        printf("len %d.\n", file_len);
                    }
                    ret = recv(clientfd, buff, file_len, MSG_WAITALL);
                    ret = write(fd, buff, strlen(buff));
                    currsize += ret;
                    percent = (double)currsize/lenth*100;
                    printf("has complete %5.2lf%%\r", percent);
                    if(ret < 1000){
                        memset(buff, 0, sizeof(buff));
                        break;
                    }
                    fflush(stdout);
                }
                printf("has complete %5.2lf%%\n", percent);
                continue;

            }
        } else if(FD_ISSET(clientfd, &rdset)) {
            recv(clientfd, buf, sizeof(buf), 0);
            printf("recv:%s\n", buf);
        }
    }
    close(clientfd);
    return 0;
}
